package com.iwinding.ladygg.ui.act;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.Constant;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.CaptchaCallback;
import com.iwinding.ladygg.net.callback.RegisterCallback;
import com.iwinding.ladygg.net.request.CaptchaReq;
import com.iwinding.ladygg.net.request.LoginReq;
import com.iwinding.ladygg.net.request.RegisterReq;
import com.iwinding.ladygg.net.response.CaptchaRp;
import com.iwinding.ladygg.net.response.RegisterRp;
import com.iwinding.ladygg.utils.LoginUtil;
import com.iwinding.ladygg.utils.StringUtil;
import com.iwinding.ladygg.utils.ToastUtil;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by hezhiyong on 2017/3/31.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener {


    private AutoCompleteTextView mEtPhone;
    private AutoCompleteTextView mEtVercode;
    private AutoCompleteTextView mEtPassword;

    private ImageView mImgCleanPhone;
    private ImageView mImgCleanPassword;
    private ImageView mImgCleanVercode;
    private Button mBtnSendVercode;
    private Button mBtnReSendVercode;
    private ImageView mImgSecure;
    private ImageView mImgVisable;

    private Button mBtnRegister;
    private TextView mTvFroeigner;

    private Timer mTimer = null;

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_register;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBackTxtResId(R.string.icane_user_login);
        setTitleResId(R.string.icane_register);
        initView();
        setListener();
    }

    void initView() {

        mEtPhone = (AutoCompleteTextView) findViewById(R.id.icane_edit_phone);
        mEtVercode = (AutoCompleteTextView) findViewById(R.id.icane_edit_vercode);
        mEtPassword = (AutoCompleteTextView) findViewById(R.id.icane_setting_password);

        mImgCleanPhone = (ImageView) findViewById(R.id.clear_phone);
        mImgCleanPassword = (ImageView) findViewById(R.id.clear_password);
        mImgCleanVercode = (ImageView) findViewById(R.id.clear_vercode);
        mImgSecure = (ImageView) findViewById(R.id.icane_secure);
        mImgVisable = (ImageView) findViewById(R.id.icane_visable);

        mBtnSendVercode = (Button) findViewById(R.id.send_ver);
        mBtnReSendVercode = (Button) findViewById(R.id.resend_ver);
        mBtnRegister = (Button) findViewById(R.id.icane_register_now);
        mTvFroeigner = (TextView) findViewById(R.id.icane_user_foreigner_register);


    }

    void setListener() {
        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanPhone.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });
        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanPassword.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });
        mEtVercode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mImgCleanVercode.setVisibility(s.length() == 0 ? View.GONE : View.VISIBLE);
            }
        });

        mImgCleanPhone.setOnClickListener(this);
        mImgCleanPassword.setOnClickListener(this);
        mImgSecure.setOnClickListener(this);
        mImgVisable.setOnClickListener(this);
        mBtnSendVercode.setOnClickListener(this);
        mBtnReSendVercode.setOnClickListener(this);
        mBtnRegister.setOnClickListener(this);
        mTvFroeigner.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_phone:
                mEtPhone.setText("");
                break;
            case R.id.clear_vercode:
                mEtVercode.setText("");
                break;
            case R.id.clear_password:
                mEtPassword.setText("");
                break;
            case R.id.icane_secure:
                mImgSecure.setVisibility(View.GONE);
                mImgVisable.setVisibility(View.VISIBLE);
                //默认状态显示密码--设置文本 要一起写才能起作用  InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
//                String pw =  mEtPassword.getText().toString();
//                mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//                mEtPassword.setText(pw);
                mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                mEtPassword.setSelection(mEtPassword.getText().length());
                break;
            case R.id.icane_visable:
                mImgVisable.setVisibility(View.GONE);
                mImgSecure.setVisibility(View.VISIBLE);
//                String pwSecure =  mEtPassword.getText().toString();
//                mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//                mEtPassword.setText(pwSecure);
                mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                mEtPassword.setSelection(mEtPassword.getText().length());
                break;
            case R.id.send_ver:
                sendVercode();
                break;
            case R.id.resend_ver:
//                sendVercode();
                break;
            case R.id.icane_register_now:
                register();
                break;
            case R.id.icane_user_foreigner_register:
                Intent intent = new Intent(this, AbroadRegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendVercode() {
        mBtnSendVercode.setEnabled(false);
        String phone = mEtPhone.getEditableText().toString();
        if (!TextUtils.isEmpty(phone)) {
            if (!StringUtil.isMobileNO(phone)) {
                ToastUtil.openMolieErrorToast(this);
                mBtnSendVercode.setEnabled(true);
                return;
            }
            //发送短信验证码
//            String requestTag = String.valueOf(System.currentTimeMillis());
            CaptchaReq req = new CaptchaReq();
            req.mobile = phone;
            RequestManager.postCaptcha(mContext, req, new CaptchaCallback(RegisterActivity.this) {

                @Override
                public void onResult(CaptchaRp captchaRp) {
                    if (captchaRp == null) {
                        return;
                    }

//                    setCaptchaCode(captchaRp.captcha);
                    mBtnSendVercode.setEnabled(true);
                    mBtnSendVercode.setText(R.string.resend_verification);

                    mBtnSendVercode.setVisibility(View.GONE);
                    setVerTimerTask();
                    mBtnReSendVercode.setVisibility(View.VISIBLE);
                }

                @Override
                public void onFail(String errorMsg) {
                    ToastUtil.openBaseToast(RegisterActivity.this, errorMsg, Toast.LENGTH_SHORT);
                }

                @Override
                public void onError(okhttp3.Call call, Exception e, int id) {
                    ToastUtil.openVerFailToast(RegisterActivity.this);
                    mBtnSendVercode.setEnabled(true);
                }
            });
        }
    }

    //设置验证码 （仅限开发模式）
    private void setCaptchaCode(final String captcha) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(captcha)) {
                    mEtVercode.setText(captcha);//
                }
            }
        });
    }


    /**
     * 注册
     */
    void register() {
        final RegisterReq registerReq = new RegisterReq();
        String phone = mEtPhone.getEditableText().toString();
        String vercode = mEtVercode.getEditableText().toString();
        String pw = mEtPassword.getEditableText().toString();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.openEmptyPhone(this);
            return;
        }
        if (!StringUtil.isMobileNO(phone)) {
            ToastUtil.openMolieErrorToast(this);
            mBtnSendVercode.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(vercode)) {
            ToastUtil.openEmptyVer(this);
            return;
        }
        if (TextUtils.isEmpty(pw)) {
            ToastUtil.openEmptyPw(this);
            return;
        }
        registerReq.mobile = phone;
        registerReq.captcha = vercode;
        registerReq.password = pw;

        RequestManager.postRegister(mContext, registerReq, new RegisterCallback() {

            @Override
            public void onResult(RegisterRp registerRp) {
                if (!TextUtils.isEmpty(registerRp.userId)) {
                    ToastUtil.openRegisterSucess(RegisterActivity.this);
                    LoginReq loginReq = new LoginReq();
                    loginReq.uname = registerReq.mobile;
                    loginReq.password = registerReq.password;
                    LoginUtil.login(RegisterActivity.this, loginReq);
                }
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(RegisterActivity.this, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    private TimerTask verTimerTask = null;

    private void setVerTimerTask() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
            verTimerTask = null;
        }

        mTimer = new Timer();
        verTimerTask = new SMSTimerTask();

        mTimer.schedule(verTimerTask, 0);
        mBtnReSendVercode.setVisibility(View.VISIBLE);
        mBtnSendVercode.setVisibility(View.GONE);
    }

    class SMSTimerTask extends TimerTask {
        @Override
        public void run() {
            for (int i = Constant.TimeConstant.VER_COUNTDOWN; i > 0; i--) {
                myHandler.sendEmptyMessage(i);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {

                }
            }
            myHandler.sendEmptyMessage(0);
        }
    }

    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what != 0) {
                mBtnReSendVercode.setText(String.format(getString(R.string.resend_verification_second), msg.what));
            } else {
                mBtnReSendVercode.setVisibility(View.GONE);
                mBtnSendVercode.setVisibility(View.VISIBLE);
            }
        }
    };


}
